﻿using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
using YouWei.Api.Common;
using YouWei.Api.Models;
using YouWei.Api.Models.WxMini;
using YouWei.Infrastructure.Dto;
using YouWei.Infrastructure.Entity;
using YouWei.Infrastructure.Service;
using YouWei.Utility;

namespace YouWei.Api.Controllers
{
    /// <summary>
    /// 用户
    /// </summary>
    public class UserController : BaseApiController
    {
        private UserInfoService _service = new UserInfoService();
        private UserRelationService _service_rela = new UserRelationService();
        private WeChartUserService _wcService = new WeChartUserService();
        private VehicleLicenseService _vlService = new VehicleLicenseService();
        private WxGroupUserService _wxGroupUserSevice = new WxGroupUserService();
        private CarGroupService _carGroupService = new CarGroupService();
        private UserCardRelaService _userCardRelaService = new UserCardRelaService();
        private UserCardService _userCardService = new UserCardService();
        private InsureLicenseNoService _insureService = new InsureLicenseNoService();
        private VehicleRemindService _vehRemindService = new VehicleRemindService();
        private CarGroupBrandService _cgBrandService = new CarGroupBrandService();
        private UserMessageService _msgService = new UserMessageService();


        #region 用户

        /// <summary>
        /// 添加用户通过电话号码
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public ResultData<UserMobileModel> AddUserMoile(PhoneNumberModel model)
        {
            //返回值格式:{"phoneNumber":"18201032670","purePhoneNumber":"18201032670","countryCode":"86","watermark":{"timestamp":1545018096,"appid":"wxb3947f8af58393c9"}}
            string result = SecurityUtility.DecodeEncryptedData(model.SessionKey, model.encryptedData, model.iv);
            JObject jobj = JObject.Parse(result);
            JToken token = jobj.GetValue("phoneNumber");
            if (token == null)
            {
                return ResultData<UserMobileModel>.Error("获取电话号码失败.");
            }
            else
            {
                //判断微信用户是否存在 没有则添加
                var wcUser = _wcService.GetByOpenID(model.OpenID);
                if (wcUser == null)
                {
                    wcUser = new WeChartUser()
                    {
                        OpenID = model.OpenID,
                        UnionID = model.UnionID,
                        NickName = model.UserName,
                        HeadImgUrl = model.UserHead,
                        CreateDate = DateTime.Now,
                        UpdateDate = DefultTime,
                        Subscribe_Time = DefultTime,
                        Mini_Time = DefultTime
                    };
                    object id = _wcService.Insert(wcUser);
                    wcUser.WeChartUserID = Convert.ToInt32(id);
                }

                UserInfo user = _service.GetUserInfoByMobile(token.Value<string>());
                if (user == null)
                {
                    if (string.IsNullOrEmpty(model.UserName))
                    {
                        model.UserName = "爱车仕_" + DateTime.Now.ToString("yyyyMMddHHmmss");
                    }

                    user = new UserInfo()
                    {
                        CreateDate = DateTime.Now,
                        UpdateDate = DefultTime,
                        IsActvie = 1,
                        UnionID = model.UnionID,
                        OpenID = model.OpenID,
                        UserName = model.UserName,
                        UserHead = model.UserHead,
                        VehicleStatus = 0,
                        Mobile = token.Value<string>()
                    };
                    object userID = _service.Insert(user);
                    user.UserID = EConvert.ToInt(userID);
                }

                return ResultData<UserMobileModel>.Success(new UserMobileModel()
                {
                    UserName = user.UserName,
                    UserID = user.UserID,
                    UserMobile = user.Mobile,
                    WeChartUserID = wcUser.WeChartUserID
                });
            }
        }

        /// <summary>
        /// 添加用户
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        [HttpPost]
        public ResultData<int> AddUser(UserInfo user)
        {
            string imgUrl = ConfigHelper.GetAppSettingValue("FileUploadUrl");
            var result = ResultData<int>.Success();
            user.UserHead = user.UserHead.Replace(imgUrl, "").Replace("/", ""); ;
            user.CreateDate = DateTime.Now;
            user.UpdateDate = DefultTime;
            user.IsActvie = 1;
            user.VehicleStatus = 0;
            object id = _service.Insert(user);

            result.data = EConvert.ToInt(id);
            return result;
        }

        /// <summary>
        /// 修改用户 信息
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost]
        public ResultData<string> EditUser(UserInfo entity)
        {
            string imgUrl = ConfigHelper.GetAppSettingValue("FileUploadUrl");
            var result = ResultData<string>.Success();
            if (entity.UserID <= 0)
            {
                result.status = -1;
                result.message = "缺少必要的参数UserId";
                return result;
            }
            var model = _service.Single(entity.UserID);
            if (model == null)
            {
                result.status = -1;
                result.message = "修改失败，用户不存在";
                return result;
            }

            model.UserHead = entity.UserHead.Replace(imgUrl, "").Replace("/", ""); ;
            model.UserDesc = entity.UserDesc;
            model.UserName = entity.UserName;
            model.Sex = entity.Sex;
            model.UpdateDate = DateTime.Now;
            _service.Update(model);
            return result;
        }

        /// <summary>
        /// 删除用户
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        [HttpPost]
        public ResultData<string> DeleteUser([FromUri] int userId)
        {
            ResultData<string> result = ResultData<string>.Success();
            if (userId <= 0)
            {
                result.status = -1;
                result.message = "删除失败，缺少必要的参数";
            }
            var model = _service.Single(userId);
            if (model != null)
            {
                model.IsActvie = 0;
                model.UpdateDate = DateTime.Now;
                _service.Update(model);
            }
            return result;
        }

        /// <summary>
        /// 获取用户信息
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        [HttpGet]
        public ResultData<UserInfo> GetUserInfo(int userId)
        {
            string url = ConfigHelper.GetAppSettingValue("FileUploadUrl");
            ResultData<UserInfo> result = ResultData<UserInfo>.Error("未查询到用户信息");
            var data = _service.Single(userId);
            if (!data.UserHead.StartsWith("http"))
            {
                data.UserHead = url + data.UserHead;
            }
            if (data != null && data.IsActvie == 1)
            {
                result.status = 0;
                result.message = "查询成功";
                result.data = data;
            }
            return result;
        }

        /// <summary>
        /// 根据OpenID获取用户信息
        /// </summary>
        /// <param name="OpenID"></param>
        /// <returns></returns>
        [HttpGet]
        public ResultData<UserInfo> GetUserInfoByOpenID(string OpenID)
        {
            string url = ConfigHelper.GetAppSettingValue("FileUploadUrl");
            ResultData<UserInfo> result = ResultData<UserInfo>.Error("未查询到用户信息");
            var data = _service.GetUserInfoByOpenID(OpenID);
            if (data != null && data.IsActvie == 1)
            {
                if (!data.UserHead.StartsWith("http"))
                {
                    data.UserHead = url + data.UserHead;
                }
                result.status = 0;
                result.message = "查询成功";
                result.data = data;
            }
            return result;
        }

        /// <summary>
        /// 绑定用户（设置上下级用户关系）
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        [HttpPost]
        public ResultData<string> SetUserRelaByMobile(UserRelaParam param)
        {
            ResultData<string> result = ResultData<string>.Success();
            var userInfo = _service.GetUserInfoByMobile(param.Mobile);
            if (userInfo != null)
            {
                var rela = new UserRelation()
                {
                    UserID = param.UserId,
                    ChildUserID = userInfo.UserID,
                    CreateDate = DateTime.Now,
                    UpdateDate = DefultTime,
                    IsActvie = 1
                };
                _service_rela.Insert(rela);
            }
            return result;
        }

        #endregion

        #region 行驶证

        /// <summary>
        /// 添加行驶证
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost]
        public ResultData<VehicleModel> SaveVehicleLicense(VehicleLicense entity)
        {
            VehicleModel vehModel = new VehicleModel();
            var model = _vlService.GetByUserPlateNum(entity.UserID, entity.PlateNo);
            if (model != null)
            {
                vehModel.VehicleLicenseID = model.VehicleLicenseID;
                CarGroup groupa = _carGroupService.GetGroupByModel(entity.ModelID);
                if (groupa != null)
                {
                    vehModel.CarGroupID = groupa.CarGroupID;
                }
                model.CreatedDate = model.CreatedDate;
                model.UpdatedDate = DateTime.Now;
                _vlService.Update(model);
                return ResultData<VehicleModel>.Success(vehModel);
            }

            //如果用户VIN不为空，则说明是识别行驶证，默认已审核
            if (string.IsNullOrWhiteSpace(entity.VIN))
            {
                //通过车牌查询保险数据，如果车牌号号码和发动机号匹配，这默认已审核
                var licenses = _insureService.GetByLicenseNo(entity.PlateNo);
                if (licenses.Exists(t => t.engine_no.Trim().Equals(entity.EngineNo.Trim())))
                {
                    entity.VehicleStatus = 2;
                }
                else
                {
                    entity.VehicleStatus = 1;
                }
            }
            else
            {
                entity.VehicleStatus = 2;
            }

            entity.CreatedDate = DateTime.Now;
            entity.UpdatedDate = DefultTime;
            entity.RegisterDate = DefultTime;
            entity.IssueDate = DefultTime;
            entity.IsActive = 1;
            object id = _vlService.Insert(entity);
            entity.VehicleLicenseID = EConvert.ToInt(id);
            vehModel.VehicleLicenseID = entity.VehicleLicenseID;

            //更新用户状态
            UserInfo usr = _service.SingleOrDefault(entity.UserID);
            if (usr != null)
            {
                usr.UpdateDate = DateTime.Now;
                if (usr.VehicleStatus != 2)
                {
                    usr.VehicleStatus = entity.VehicleStatus;
                }
                _service.Update(usr);
            }
            vehModel.VehicleStatus = usr.VehicleStatus;

            //添加用户群组关系
            var group = _cgBrandService.GetCarGroupBrandByModel(entity.ModelID);
            if (group != null)
            {
                vehModel.CarGroupID = group.CarGroupID;
                _wxGroupUserSevice.Insert(new WxGroupUser()
                {
                    CarGroupID = group.CarGroupID,
                    CreateDate = DateTime.Now,
                    IsActive = 1,
                    UpdateDate = DefultTime,
                    UserID = usr.UserID,
                    OpenID = usr.OpenID,
                    UnionID = usr.UnionID
                });
            }

            //添加车主卡
            var rela = _userCardRelaService.GetByUser(usr.UserID);
            if (rela == null)
            {
                var card = _userCardService.GetList().Where(t => t.Level == 1).FirstOrDefault();
                _userCardRelaService.Insert(new UserCardRela()
                {
                    CardCode = _userCardRelaService.CreateCardCode(usr.UserID),
                    CreatedDate = DateTime.Now,
                    IsActive = 1,
                    UpdatedDate = DefultTime,
                    UserId = usr.UserID,
                    CardId = card.CardId
                });
            }

            //添加用户提醒
            VehicleRemind vrObj = _vehRemindService.GetInfoByVehicleID(vehModel.VehicleLicenseID);
            if (vrObj == null)
            {
                vrObj = new VehicleRemind();
                vrObj.VehicleLicenseID = entity.VehicleLicenseID;
                vrObj.CreatedDate = DateTime.Now;
                vrObj.IsActive = 1;
                vrObj.NextMaintainDate = DefultTime;
                vrObj.MaintainDate = DefultTime;
                vrObj.NextInsureDate = DefultTime;
                vrObj.InsureExpireDate = DefultTime;
                vrObj.NextYearCheckDate = DefultTime;
                vrObj.FirstRegisterDate = DefultTime;
                vrObj.IsViolate = 0;
                vrObj.IsYearCheck = 0;
                vrObj.IsInsure = 0;
                vrObj.IsMaintain = 0;
            }

            bool isInsert = false;
            if (!string.IsNullOrEmpty(entity.EngineNo))
            {
                isInsert = true;
                vrObj.EngineCode = entity.EngineNo;
            }
            if (entity.RegisterDate.Year > 1900)
            {
                isInsert = true;
                vrObj.FirstRegisterDate = entity.RegisterDate;
                vrObj.NextYearCheckDate = GetLittleCarYearCheckDate(vrObj.FirstRegisterDate);
                vrObj.InsureExpireDate = entity.RegisterDate;
                DateTime dt = DateTime.Now;
                if (entity.RegisterDate <= dt)
                {
                    TimeSpan ts = new TimeSpan(dt.Ticks - entity.RegisterDate.Ticks);
                    vrObj.NextInsureDate = entity.RegisterDate.AddYears((ts.Days / 365) + 1);
                }
                else
                {
                    vrObj.NextInsureDate = entity.RegisterDate;
                }
            }
            if (isInsert)
            {
                _vehRemindService.Insert(vrObj);
            }

            return ResultData<VehicleModel>.Success(vehModel);
        }

        /// <summary>
        /// 获取当前用户行驶证信息
        /// </summary>
        /// <param name="UserID"></param>
        /// <returns></returns>
        [HttpGet]
        public ResultData<List<VehicleLicense>> VehicleLicenses(int UserID)
        {
            var data = _vlService.GetByUser(UserID);
            return ResultData<List<VehicleLicense>>.Success(data);
        }

        /// <summary>
        /// 获取详情
        /// </summary>
        /// <param name="vehicleId"></param>
        /// <returns></returns>
        [HttpGet]
        public ResultData<VehicleLicense> VehicleLicense(int vehicleId)
        {
            var data = _vlService.SingleOrDefault(vehicleId);
            return ResultData<VehicleLicense>.Success(data);
        }
        #endregion

        /// <summary>
        /// 获取小客车年检时间
        /// </summary>
        /// <param name="dt"></param>
        /// <returns></returns>
        private DateTime GetLittleCarYearCheckDate(DateTime dt)
        {
            DateTime newDt = DateTime.Now;
            int year = newDt.Year - dt.Year;

            if (year <= 6)
            {
                if (dt.AddYears(6) >= newDt.Date)
                {
                    return dt.AddYears(6);
                }
                else
                {
                    return dt.AddYears(7);
                }

            }
            else if (year > 6 && year < 15)
            {
                if (dt.AddYears(year) >= newDt.Date)
                {
                    return dt.AddYears(year);
                }
                else
                {
                    return dt.AddYears(year + 1);
                }

            }
            else
            {
                if (year == 15)
                {
                    if (dt.Month < 7)
                    {
                        int m = 6;
                        if (newDt.Month - dt.Month > 6)
                        {
                            m = 12;
                        }
                        else if (newDt.Month - dt.Month == 6 && newDt.Day > dt.Day)
                        {
                            m = 12;
                        }
                        return dt.AddYears(year).AddMonths(m);
                    }
                    else
                    {
                        if (dt.AddYears(year) >= newDt.Date)
                        {
                            return dt.AddYears(year);
                        }
                        else
                        {
                            return dt.AddYears(year).AddMonths(6);
                        }
                    }

                }
                else
                {
                    return dt.AddYears(year).AddMonths(6);
                }
            }

        }

        /// <summary>
        /// 更新行驶证信息
        /// </summary>
        /// <returns></returns>
        public ResultData<bool> UpdateVehicleLicense(ReqVehicle entity)
        {
            var model = _vlService.GetByUserPlateNum(entity.UserId, entity.PlateNo);
            if (model != null)
            {
                if (model.VehicleStatus != 3)
                {
                    return ResultData<bool>.Error("当前状态不能修改");
                }
                model.PlateNo = entity.EditPlateNo;
                model.Owner = entity.Owner;
                model.EngineNo = entity.EngineNo;
                model.UpdatedDate = DateTime.Now;
                _vlService.Update(model);
                return ResultData<bool>.Success(true);
            }
            else
            {
                return ResultData<bool>.Error("找不到行驶证信息");
            }
        }

        #region 用户消息
        /// <summary>
        /// 获取用户消息数量
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        [HttpGet]
        public ResultData<int> GetUserMessageCount(int userId)
        {
            ResultData<int> result = new ResultData<int>();
            try
            {
                var data = _msgService.GetMessageCount(userId);
                result.status = 0;
                result.message = "查询成功";
                result.data = data;
            }
            catch (Exception ex)
            {
                result = ResultData<int>.Error("查询失败," + ex.Message);
            }          
            return result;
        }

        /// <summary>
        /// 更新用户查看状态
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        [HttpPost]
        public ResultData<bool> UpdateUserMessageViewStatus(int userId)
        {
            ResultData<bool> result = new ResultData<bool>();
            try
            {
                var data = _msgService.UpdateMessageStatus(userId);
                result.status = 0;
                result.message = "更新成功";
                result.data = data;
            }
            catch (Exception ex)
            {
                result = ResultData<bool>.Error("更新失败," + ex.Message);
            }
            return result;
        }
        #endregion
    }
}